package com.framework.buss.bridge.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.framework.buss.bridge.model.WordTree;
import com.framework.buss.bridge.service.IWordByteService;
import com.framework.buss.bridge.service.IWordTreeService;
import com.framework.buss.bridge.vo.WordTreeSelectedVO;
import com.framework.common.domain.ResultData;
import com.framework.common.model.SelectTreeModel;
import com.framework.common.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

 /**
 * @Description: 模板word目录表
 * @Author: jeecg-boot
 * @Date:   2023-08-14
 * @Version: V1.0
 */
@Api(tags="模板word目录表")
@RestController
@RequestMapping("/bridge/wordTree")
@Slf4j
public class WordTreeController {
	@Autowired
	private IWordTreeService wordTreeService;
	@Autowired
	private IWordByteService wordByteService;

	 /**
	  * @param treeSelectedVO
	  * @return
	  */
	 @ApiOperation(value="AI报告-目录查询", notes="AI报告-目录查询")
	 @GetMapping(value = "/list")
	 public ResultData<List<WordTreeSelectedVO>> listAll(WordTreeSelectedVO treeSelectedVO) {
		 List<WordTreeSelectedVO> pageList = wordTreeService.listAll(treeSelectedVO);
		 return ResultData.data(pageList);
	 }

	/**
	 * 分页列表查询
	 *
	 * @param wordTree
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@ApiOperation(value="模板word目录表-分页列表查询", notes="模板word目录表-分页列表查询")
	@GetMapping(value = "/rootList")
	public ResultData<IPage<WordTree>> queryPageList(WordTree wordTree,
													 @RequestParam(name = "hasQuery") Boolean hasQuery,
													 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
        if(hasQuery != null && "true".equals(hasQuery)){
			LambdaQueryWrapper<WordTree> queryWrapper = new LambdaQueryWrapper();
			queryWrapper.orderByAsc(WordTree::getSort);
            List<WordTree> list = wordTreeService.queryTreeListNoPage(queryWrapper);
            IPage<WordTree> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return ResultData.data(pageList);
        }else{
            String parentId = wordTree.getPid();
            if (StringUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            wordTree.setPid(null);
			LambdaQueryWrapper<WordTree> queryWrapper = new LambdaQueryWrapper();;
            // 使用 eq 防止模糊查询
            queryWrapper.eq(WordTree::getPid, parentId);
            Page<WordTree> page = new Page<WordTree>(pageNo, pageSize);
            IPage<WordTree> pageList = wordTreeService.page(page, queryWrapper);
            return ResultData.data(pageList);
        }
	}

	 /**
	  * 【vue3专用】加载节点的子数据
	  *
	  * @param pid
	  * @return
	  */
	 @RequestMapping(value = "/loadTreeChildren", method = RequestMethod.GET)
	 public ResultData<List<SelectTreeModel>> loadTreeChildren(@RequestParam(name = "pid") String pid) {
		List<SelectTreeModel> ls = wordTreeService.queryListByPid(pid);
		return ResultData.data(ls);
	 }

	 /**
	  * 【vue3专用】加载一级节点/如果是同步 则所有数据
	  *
	  * @param async
	  * @param pcode
	  * @return
	  */
	 @RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
	 public ResultData<List<SelectTreeModel>> loadTreeRoot(@RequestParam(name = "async") Boolean async, @RequestParam(name = "pcode") String pcode) {
		 List<SelectTreeModel> ls = wordTreeService.queryListByCode(pcode);
		 if (!async) {
			 loadAllChildren(ls);
		 }
		 return ResultData.data(ls);
	 }

	 /**
	  * 【vue3专用】递归求子节点 同步加载用到
	  *
	  * @param ls
	  */
	 private void loadAllChildren(List<SelectTreeModel> ls) {
		 for (SelectTreeModel tsm : ls) {
			 List<SelectTreeModel> temp = wordTreeService.queryListByPid(tsm.getKey());
			 if (temp != null && temp.size() > 0) {
				 tsm.setChildren(temp);
				 loadAllChildren(temp);
			 }
		 }
	 }

	 /**
      * 获取子数据
      * @param wordTree
      * @return
      */
	@ApiOperation(value="模板word目录表-获取子数据", notes="模板word目录表-获取子数据")
	@GetMapping(value = "/childList")
	public ResultData<IPage<WordTree>> queryPageList(WordTree wordTree) {
		QueryWrapper<WordTree> queryWrapper = new QueryWrapper<>();
		if (!StringUtils.isEmpty(wordTree.getName())) {
			queryWrapper.like("name", wordTree.getName());
		}
		queryWrapper.orderByAsc("sort");
		List<WordTree> list = wordTreeService.list(queryWrapper);
		IPage<WordTree> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
		return ResultData.data(pageList);
	}

    /**
      * 批量查询子节点
      * @param parentIds 父ID（多个采用半角逗号分割）
      * @return 返回 IPage
      * @param parentIds
      * @return
      */
    @ApiOperation(value="模板word目录表-批量获取子数据", notes="模板word目录表-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public ResultData getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<WordTree> queryWrapper = new QueryWrapper<>();
			queryWrapper.orderByAsc("sort");
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            List<WordTree> list = wordTreeService.list(queryWrapper);
            IPage<WordTree> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return ResultData.data(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultData.error("批量查询子节点失败：" + e.getMessage());
        }
    }
	
	/**
	 *   添加
	 *
	 * @param wordTree
	 * @return
	 */
	@ApiOperation(value="模板word目录表-添加", notes="模板word目录表-添加")
	@PostMapping(value = "/add")
	public ResultData<String> add(@RequestBody WordTree wordTree) {
		wordTreeService.addWordTree(wordTree);
		return ResultData.success("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param wordTree
	 * @return
	 */
	@ApiOperation(value="模板word目录表-编辑", notes="模板word目录表-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public ResultData<String> edit(@RequestBody WordTree wordTree) {
		wordTreeService.updateWordTree(wordTree);
		return ResultData.success("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="模板word目录表-通过id删除", notes="模板word目录表-通过id删除")
	@DeleteMapping(value = "/delete")
	public ResultData<String> delete(@RequestParam(name="id",required=true) String id) {
		wordTreeService.deleteWordTree(id);
		return ResultData.success("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@ApiOperation(value="模板word目录表-批量删除", notes="模板word目录表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public ResultData<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.wordTreeService.removeByIds(Arrays.asList(ids.split(",")));
		return ResultData.success("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="模板word目录表-通过id查询", notes="模板word目录表-通过id查询")
	@GetMapping(value = "/queryById")
	public ResultData<WordTree> queryById(@RequestParam(name="id",required=true) String id) {
		WordTree wordTree = wordTreeService.getById(id);
		if(wordTree==null) {
			return ResultData.error("未找到对应数据");
		}
		return ResultData.data(wordTree);
	}

	 @RequestMapping(value = "/saveWord")
	 public void saveWord(HttpServletRequest request, HttpServletResponse response) throws IOException {
		 wordByteService.saveWord(request, response);
	 }

	 @RequestMapping(value = "/loadWord")
	 @ResponseBody
	 public void loadWord(HttpServletRequest request, HttpServletResponse response) {
		 String fileId = request.getParameter("id");
    	wordByteService.loadWord(fileId, response);
	 }
}
